package com.tt.job.schedule;

import com.tt.job.common.cluster.InvokeResult;
import com.tt.job.common.cluster.LoadBalance;
import com.tt.job.common.cluster.http.HttpInvocation;
import com.tt.job.common.cluster.http.HttpInvoker;
import com.tt.job.common.cluster.loadbalance.LeastActiveLoadBalance;
import com.tt.job.common.cluster.loadbalance.RandomLoadBalance;
import com.tt.job.common.cluster.loadbalance.RoundRobinLoadBalance;
import com.tt.job.common.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

/**
 * 事件服务
 */
@Service
public class EventService {
    private final static Logger logger = LoggerFactory.getLogger(EventService.class);
    private volatile LoadBalance<HttpInvoker> apiLoad = null;
    @Value("${job.url:http://localhost:8080,http://localhost:8090}")
    private String asyncJobPrefix;
    @Value("${job.balance:random}")
    private String balanceType;
    @Value("${job.pool:16}")
    private Integer poolSize;

    /**
     * 发送异步任务
     *
     * @param group
     * @param jobClass
     * @param params
     * @param stack
     * @throws EventException
     */
    public void sendAsync(String group, String jobClass, Integer delayLevel,
                          HashMap<String, String> params, Stack<RollbackOperator> stack, String... key) throws EventException {
        initApiLoader();
        Map<String, String> combingParams = new HashMap<>(params);
        if (stack != null && stack.size() > 0) {
            combingParams.put("#stack", JsonUtil.encodeString(stack));
        }
        HttpInvocation invocation = new HttpInvocation("event");
        invocation.setMethod(HttpInvocation.METHOD_POST);
        invocation.setPath("/schedule/async");
        invocation.setQueryString(String.format("group=%s&jobClass=%s&delayLevel=%s&key=%s", group, jobClass, delayLevel, key == null ? "" : key));
        invocation.setContentType(HttpInvocation.CONTENT_TYPE_JSON);

        invocation.setBody(JsonUtil.encodeByte(combingParams));

        HttpInvoker invoker = apiLoad.select(invocation);
        Map result;
        try {
            InvokeResult<Map> invokeResult = invoker.invoke(invocation, Map.class);
            result = invokeResult.getResult();
        } catch (Exception e) {
            logger.error("发送异步任务异常。invoker:{}, group:{}, class:{}, data:{}", invoker, group, jobClass, JsonUtil.encodeString(params), e);
            throw new EventException("异步任务发送异常", group, jobClass, params, e);
        }
        boolean success = result != null && "0000".equals(result.get("code"));
        if (!success) {
            logger.error("发送异步任务失败. group:{}, class:{}, params:{}", group, jobClass, JsonUtil.encodeString(params));
            throw new EventException("异步任务发送失败", group, jobClass, params, null);
        }
    }

    /**
     * @param name
     * @param params
     * @param stack
     * @throws EventException
     */
    public void sendEvent(String group, String name, HashMap<String, String> params,
                          Stack<RollbackOperator> stack, String... key) throws EventException {
        initApiLoader();
        Map<String, String> combingParams = new HashMap<>(params);
        if (stack != null && stack.size() > 0) {
            combingParams.put("#stack", JsonUtil.encodeString(stack));
        }
        HttpInvocation invocation = new HttpInvocation("event");
        invocation.setMethod(HttpInvocation.METHOD_POST);
        invocation.setPath("/schedule/event");
        invocation.setQueryString(String.format("group=%s&event=%s&key=%s", group, name, key == null ? "" : key));
        invocation.setContentType(HttpInvocation.CONTENT_TYPE_JSON);

        invocation.setBody(JsonUtil.encodeByte(combingParams));

        HttpInvoker invoker = apiLoad.select(invocation);
        Map result;
        try {
            InvokeResult<Map> invokeResult = invoker.invoke(invocation, Map.class);
            result = invokeResult.getResult();
        } catch (Exception e) {
            logger.error("发送事件异常。invoker:{}, group:{}, event:{}, data:{}", invoker, group, name, JsonUtil.encodeString(params), e);
            throw new EventException("事件发送异常", group, name, params, e);
        }
        boolean success = result != null && "0000".equals(result.get("code"));
        if (!success) {
            logger.error("发送事件失败. group:{}, name:{}, params:{}", group, name, JsonUtil.encodeString(params));
            throw new EventException("事件发送失败", group, name, params, null);
        }
    }

    private void initApiLoader() {
        if (apiLoad == null) {
            synchronized (this) {
                if (apiLoad == null) {
                    String[] prefixes = asyncJobPrefix.split(",");
                    List<HttpInvoker> invokers = HttpInvoker.getInvokers("job.event.invoker", 20, prefixes);
                    switch (balanceType) {
                        case RandomLoadBalance.NAME:
                            apiLoad = new RandomLoadBalance<>(invokers);
                            break;
                        case LeastActiveLoadBalance.NAME:
                            apiLoad = new LeastActiveLoadBalance<>(invokers);
                            break;
                        case RoundRobinLoadBalance.NAME:
                            apiLoad = new RoundRobinLoadBalance<>(invokers);
                            break;
                        default:
                            logger.error("job.api.balance:{} 配置的均衡模式不支持!", balanceType);
                    }
                }
            }
        }
    }
}
